var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var orderId = '';
var frm = '';
var serviceType = '退货并退款';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,
    uid: '',
    token: '',
    
    cancels: [
      { name: '1', value: '退货并退款', checked: 'false' },
      // { name: '2', value: '退款不退货', checked: 'true' },
    ],

    uploadImg: [],
    imgWH: 0,

    deliveName: [],
    actionSheetHidden: true,
    selectedDeliveItem: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    orderId = options.orderid;
    frm = options.frm;
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var img_w_h = (res.windowWidth - 44) / 4
        that.setData({
          imgWH: img_w_h,
          tc: app.get_tc()
        });
      }
    })
    var b_nav_data = app.getBottomNavData('order-service/order-service', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

     wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    this.getDeliverName();
    //当前登录用户信息
    app.getLoginUserInfo(function (res) {
      //更新数据
      that.setData({
        uid: res.uid,
        token: res.token,
      });
    });

    
  },

  cancelChange: function (e) {
    serviceType = e.detail.value;
  },

  //获取快递 名称
  getDeliverName: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getexpress",
    };
    util.api({
      data: params,
      method: 'GET',
      success: function (responseData) {
        var resData = responseData.data;
        console.log("快递名称：", resData);
        if (resData.msg) {
          app.dialog(resData.msg, 'loading');
        } else {
          that.setData({
            deliveName: resData
          });
        }
      }
    });
  },

  showSelect: function () {
    this.setData({
      actionSheetHidden: false
    });
  },

  selectAction: function (event) {
    var value = event.currentTarget.dataset.link;
    this.setData({
      selectedDeliveItem: value,
      actionSheetHidden: true
    });
  },
  actionSheetTap: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  actionSheetbindchange: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },

  //申请售后
  cancelorder: function (event) {
    app.saveFormId(e.detail.formId);
    var that = this;

    if (!this.data.selectedDeliveItem) {
      app.dialog("请选择快递", 'loading');
      return;
    }
    var deliveNo = event.detail.value.deliveNo;
    if (!deliveNo) {
      app.dialog("请输入快递单号", 'loading');
      return;
    }

    var cusReason = event.detail.value.reason;
    if (!cusReason) {
      app.dialog("请输入申请原因", 'loading');
      return;
    }
    var reason = serviceType + "; " + cusReason;
    
    //图片
    var photos = this.data.uploadImg;//选择的图片 	图片的本地文件路径列表
    var photos_param = '';
    if (photos && photos.length > 0) {
      //data 里面是参数  我不知道是不是用这个接口  你看着改吧  再把内容和图片放里就好了
      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      photos_param = photos.map(function (item) { return item.replace('wxfile://tmp_', util.upyun_imgHost + '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(',');
    }

    var privatekey = utilMd5.hexMD5(this.data.uid + 'refundorder' + this.data.token);
    var data = {
      ac: "refundorder",
      privatekey: privatekey,
      uid: this.data.uid,
      fendanid: orderId,
      reason: reason,
      cancelimg: photos_param,
      c_expid: that.data.selectedDeliveItem.id,
      c_expnum: deliveNo
    };
    console.log("申请售后 参数", data);
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var resData = responseData.data;
        console.log("申请售后 返回", resData);
        if (resData.res) {
          //刷新
          var delta = 1;
          if (frm == 'detail') {
            delta = 2;
          }
          app.dialogToast('申请已提交', 'success', function () {
            wx.navigateBack({
              delta: delta
            })
          })
        } else {
          app.dialog(resData.msg, 'loading');
        }
      }
    });
  },


  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length >= 9) {
      app.dialog('最多上传9张图片', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        // for (var photoi = 0; photoi < tempFileCount; photoi++) {
        //   var imageSrc = res.tempFilePaths[photoi]
        //   var nowd = new Date();
        //   var nowm = nowd.getMonth() + 1;
        //   nowm = nowm.toString();
        //   if (parseInt(nowm) < 10) {
        //     nowm = '0' + nowm;
        //   }
        //   var nowda = nowd.getDate();
        //   nowda = nowda.toString();
        //   if (parseInt(nowda) < 10) {
        //     nowda = '0' + nowda;
        //   }
        //   var nowhour = nowd.getHours();
        //   nowhour = nowhour.toString();
        //   if (parseInt(nowhour) < 10) {
        //     nowhour = '0' + nowhour;
        //   }
        //   var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
        //   upyun.upload({
        //     localPath: imageSrc,
        //     remotePath: imgUrl,
        //     success: function (res) {
        //       uploadCount++;
        //       if (uploadCount == tempFileCount) {
        //         wx.showToast({
        //           title: '上传成功',
        //           icon: 'success',
        //           duration: 1000
        //         })
        //       }
        //       // jobj.put("url", recordUrl);
        //       // jobj.put("name", imgFileName);
        //       // jobj.put("type", resJob.optString("mimetype"));
        //       // jobj.put("size", resJob.optInt("file_size"));
        //       // jobj.put("hash", resJob.optString("sign"));
        //       // jobj.put("extension", resJob.optString("image-type"));
        //       // jobj.put("save_path", savePath);
        //       // jobj.put("save_name", savename);
        //       // jobj.put("width", resJob.optInt("image-width"));
        //       // jobj.put("height", resJob.optInt("image-height"));
        //     },
        //     fail: function ({ errMsg }) {
        //       uploadCount++;
        //       if (uploadCount == tempFileCount) {
        //         wx.showToast({
        //           title: '上传成功',
        //           icon: 'success',
        //           duration: 1000
        //         })
        //       }
        //       console.log('uploadImage fail, errMsg is', errMsg)
        //     }
        //   })
        // }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})